/*
 * Copyright 2020 wangruiCoder owner
 */

package org.disk.frame.logger.autoconfigure;

import org.disk.frame.logger.client.InvokeLogClient;
import org.disk.frame.logger.client.LogClient;
import org.disk.frame.logger.config.DiskFrameLoggerConfiguration;
import org.disk.frame.logger.config.HttpLogInterceptorConfig;
import org.disk.frame.logger.listener.HttpLogListener;
import org.disk.frame.plugin.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * 日志组件自动装配类
 * <p>详细描述</p>
 *
 * @author kyrie 2021/4/23 9:13 上午
 * @since jdk1.8
 */
@Configuration
@Import(value = RedisService.class)
@ConditionalOnProperty(value = "disk.frame.logger.enable",matchIfMissing = true)
@EnableConfigurationProperties
@EnableAsync
public class DiskFrameLoggerAutoConfiguration {
    private final Logger logger = LoggerFactory.getLogger(DiskFrameLoggerAutoConfiguration.class);

    @Bean
    @ConditionalOnMissingBean(value = DiskFrameLoggerConfiguration.class,search = SearchStrategy.CURRENT)
    public DiskFrameLoggerConfiguration diskFrameLoggerConfig(){
        return new DiskFrameLoggerConfiguration();
    }

    @Bean
    @ConditionalOnBean(value = DiskFrameLoggerConfiguration.class)
    public LogClient logClient(DiskFrameLoggerConfiguration diskFrameLoggerConfig) throws Exception{
        InvokeLogClient invokeClient = new InvokeLogClient();
        LogClient logClient;
        try {
            logClient = invokeClient.getClient(diskFrameLoggerConfig);
        } catch (Exception e) {
            logger.error("日志组件启动失败：{}",e.getMessage());
            throw new Exception(e.getMessage());
        }
        logger.info("disk frame logger is successful");
        return logClient;
    }

    @Bean
    @ConditionalOnMissingBean(value = HttpLogListener.class,search = SearchStrategy.CURRENT)
    public HttpLogListener logListener(){
        return new HttpLogListener();
    }

    @Bean
    @ConditionalOnMissingBean(value = HttpLogInterceptorConfig.class,search = SearchStrategy.CURRENT)
    public HttpLogInterceptorConfig logInterceptorConfig(){
        return new HttpLogInterceptorConfig();
    }

}

